﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using COFE.Core.Utils;
using System.IO;

namespace COFE.Web
{
    /// <summary>
    /// Utils related to serialization of an object.
    /// </summary>
    public static class SerializationUtils
    {
        /// <summary>
        /// Obsoluted, Convert from a dictionary to Json string.
        /// </summary>
        /// <param name="propertyValueDic"></param>
        /// <returns></returns>
        public static string ToJson(Dictionary<XName, object> propertyValueDic)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("{");

            foreach (var propVal in propertyValueDic)
                switch (propVal.ToString().ToLower())
                {
                    case "int32":
                    case "int64":
                        sb.AppendLine(String.Format("\"{0}\" : {1}", propVal.Key.LocalName, propVal.Value));
                        break;
                    default:
                        sb.AppendLine(String.Format("\"{0}\" : \"{1}\"", propVal.Key.LocalName, propVal.Value));
                        break;
                }

            sb.AppendLine("}");

            return sb.ToString();
        }

        /// <summary>
        /// Convert from a string to memory stream.
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static Stream ToMemoryStream(string text)
        {
            var ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            sw.Write(text);
            sw.Flush();
            ms.Seek(0, SeekOrigin.Begin);            
            return ms;
        }
    }
}
